<template>
    <el-menu
      :default-active='activeIndex'
      background-color="#2d3a4b"
      text-color="#fff"
      active-text-color="#2d8cf0"
      class="el-menu-vertical"
      :unique-opened="true"
      :router='true'
      mode="vertical"
      :collapse="collapse">
        <sidebar-item v-for="(item,index) in routesData" :key='index' :sideBar='item'></sidebar-item>
    </el-menu>
</template>

<script>
import sidebarItem from '@/components/sidebarItem'
import bus from './bus.js'
export default {
  name: 'sidebar',
  components: {sidebarItem},
  data () {
    return {
      collapse: false,
      routesData: [],
      activeIndex: ''
    }
  },
  created () {
    bus.$on('collapse', msg => {
      this.collapse = msg
    })
    if (!this.routesData.length) {
      let routes = this.$router.options.routes.filter(item => {
        return !item.hidden
      })
      this.routesData = this.handleRoutes(JSON.parse(JSON.stringify(routes)))
    }
    this.activeIndex = this.$route.path
  },
  methods: {
    /**
     * @method 处理路由是否显示
     */
    handleRoutes (routes, result = {routes: [], url: ''}) {
      for (let i = 0, len = routes.length; i < len; i++) {
        if (!routes[i].hidden) {
          if (routes[i].children && routes[i].children.length) {
            let newUrl = this.handleUrl(result.url, routes[i].path)
            routes[i].meta.url = newUrl
            try {
              routes[i].children = this.handleRoutes(routes[i].children, {routes: [], url: newUrl})
            } finally {
              if (routes[i].children.length === 1) {
                routes[i] = routes[i].children[0]
              }
            }
          } else {
            let newUrl = this.handleUrl(result.url, routes[i].path)
            routes[i].meta.url = newUrl
          }
          result.routes.push(routes[i])
        }
      }
      return result.routes
    },
    handleUrl (topUrl, url) {
      let resultUrl = ((topUrl.length === 1 && topUrl[0] === '/' ? '' : topUrl) + (url ? url.indexOf('/') === 0 ? url : '/' + url : ''))
      return resultUrl
    }
  }
}
</script>

<style lang="scss" scoped>
    .el-menu{
        border-right: none;
    }
    .el-menu-vertical:not(.el-menu--collapse) {
      width: 200px;
      min-height: 400px;
    }
</style>
